package com.ming.transaction.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ming.transaction.common.Constant;
import com.ming.transaction.entity.User;
import com.ming.transaction.exception.ServiceException;
import com.ming.transaction.service.IUserService;
import com.ming.transaction.util.jwtTokenUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * jwt 拦截器
 * @author: Chenming
 * @date 2023/5/3 22:55
 */
public class jwtInterceptor implements HandlerInterceptor {

    @Resource
    private jwtTokenUtil tokenUtil;
    
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(405,"Token为空,请登录!");
        }

        // 获取 token 中的 用户Number
        String userNumber;
        try {
            userNumber = tokenUtil.getUserNameFromToken(token);
            request.getSession().setAttribute("Number",userNumber);
        } catch (Exception e) {
            throw new ServiceException(405,"Token 认证失败，请重新登录!");
        }

        // 判断用户是否存在
        String key = Constant.Redis_User + token;
        // 从 Redis 判断用户是否存在
        String s = stringRedisTemplate.opsForValue().get(key);
        if ( userNumber.equals(s) ){
            return true;
        }else{
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("number", userNumber);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                throw new ServiceException(405, "用户不存在，请重新登录");
            }
            stringRedisTemplate.opsForValue().set(key,userNumber,Constant.Redis_User_TTL, TimeUnit.MINUTES);
        }
        return true;
    }
}
